package com.shigu.cron;

import com.opentae.data.mall.beans.CashApply;
import com.opentae.data.mall.interfaces.CashApplyMapper;
import com.shigu.account.service.UserService;
import com.shigu.constant.enums.PageUri;
import com.shigu.constant.enums.SystemConstant;
import com.shigu.constant.service.SystemConstantService;
import com.shigu.util.MoneyUtil;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.*;

/*
 * create by  过儿  2019-11-18
 * 定时提现审核
 */
@Component
public class CashExaminTask {
    @Autowired
    UserService userService;
    @Autowired
    CashApplyMapper cashApplyMapper;

    @Autowired
    SystemConstantService systemConstantService;

    //提现的集合
    private static Set<Long> cashSet = null;

    //
    private static final SimpleDateFormat sdf1 = new SimpleDateFormat("yyyy-MM-dd");
    private static final SimpleDateFormat sdf2 = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");

    @Scheduled(cron="0/10 * * * * ?")
    public void autoCash() throws ParseException {
       //当天开始时间和结束时间
        String date = sdf1.format(new Date());

        Date start = sdf2.parse(date + " 00:00:00");
        Date end = sdf2.parse(date + " 23:59:59");
        if(cashSet == null){
            //如果集合为空
            cashSet = new TreeSet<>();
        }
        Map<String, String> map = systemConstantService.selPageConstant(PageUri.system.toString());
        Double cashMoney = Double.valueOf(map.get(SystemConstant.cashLimit.toString()));

        List list = new ArrayList(cashSet);
        //查出待审核记录,set中除外
        List<CashApply> applies = cashApplyMapper.autoCashList(list, start, end);
        for (CashApply apply : applies) {
           /*
           * 一个用户可能同时多条，当有一条提现之后超过限额，
           * 就把申请id放入set中
           * */
           if( !cashSet.contains(apply.getApplyId()) ){//集合中过滤了该申请
               //判断当天提现额度是否超过金额，超过则放入set中
               Double hasCash = cashApplyMapper.userMoneyCash(apply.getMallUserId(), start, end);
               Double calc = MoneyUtil.add(Double.toString(hasCash), Double.toString(apply.getMoney()));
               if(calc > cashMoney){
                   cashSet.add(apply.getApplyId());
               }else {
                   //可以提现
                   try {
                       userService.examineCash(apply.getApplyId(),true,"",1L);
                   } catch (Exception e) {
                       e.printStackTrace();
                   }
               }
           }
        }
    }

    //每天凌晨初始化 cashSet
    @Scheduled(cron = "0 0 0 1/1 * ? ")
    public void clearCashSet(){
        cashSet = new TreeSet<>();
    }
}
